# coding: utf-8
import os
import sys
import shutil
import time
import math
import cv2
import random


# Magic Number，不设置可能无法正常执行，请根据具体截图从上到下按需设置
under_game_score_y = 300     # 截图中刚好低于分数显示区域的 Y 坐标，300 是 1920x1080 的值，2K 屏、全面屏请根据实际情况修改

target_h_start = 620
target_w_start = 120

# 按照(+/-0.01)左右进行调节,步子大了就调小一点，小了就调大一点
press_coefficient = 1.37    # 长按的时间系数，请自己根据实际情况调节

swipe_x1, swipe_y1, swipe_x2, swipe_y2 = 520, 1580, 520, 1580     # 模拟按压的起始点坐标，需要自动重复游戏请设置成“再来一局”的坐标
piece_base_height_1_2 = 25   # 二分之一的棋子底座高度，可能要调节
piece_body_width = 80       # 棋子的宽度，比截图中量到的稍微大一点比较安全，可能要调节



screenshot_backup_dir = 'screenshot_backups/'
if not os.path.isdir(screenshot_backup_dir):
        os.mkdir(screenshot_backup_dir)

def pull_screenshot():
    flag = os.system('adb shell screencap -p /sdcard/1.png')
    if flag == 1:
        print('请安装ADB并配置环境变量')
        sys.exit()
    os.system('adb pull /sdcard/1.png .')


def backup_screenshot(ts):
    # 为了方便失败的时候 debug
    if not os.path.isdir(screenshot_backup_dir):
        os.mkdir(screenshot_backup_dir)
    shutil.copy('1.png', '{}{}.png'.format(screenshot_backup_dir, ts))

def save_debug_creenshot(ts, im, piece_x, piece_y, board_x, board_y):
    # draw = ImageDraw.Draw(im)
    # draw.line((piece_x, piece_y) + (board_x, board_y), fill=2, width=3)
    # del draw
    # im.save("{}{}_d.png".format(screenshot_backup_dir, ts))
    cv2.line(im,(piece_x,piece_y),(board_x,board_y),(0,255,0))
    cv2.imwrite("{}{}_d.png".format(screenshot_backup_dir, ts),im)


def jump(distance):
    press_time = distance * press_coefficient
    press_time = max(press_time, 200)   # 设置 200 ms 是最小的按压时间
    press_time = int(press_time * random.uniform(0.95,1.05))
    cmd = 'adb shell input swipe {} {} {} {} {}'.format(swipe_x1 * random.uniform(0.95,1.05),
                                                        swipe_y1 * random.uniform(0.95,1.05),
                                                        swipe_x2 * random.uniform(0.95,1.05),
                                                        swipe_y2 * random.uniform(0.95,1.05), press_time)
    print(cmd)
    os.system(cmd)


def find_piece_and_board(im):
    # w, h = im.size
    size = im.shape
    w = size[1]
    h = size[0]

    piece_x_sum = 0
    piece_x_c = 0
    piece_y_max = 0
    board_x = 0
    board_y = 0

    for i in range(target_h_start,h - target_h_start, 2):
        for j in range(target_w_start, w - target_w_start):
            # pixel = im.getpixel((j, i))
            pixel = im[i,j]
            # 根据棋子的最低行的颜色判断，找最后一行那些点的平均值，这个颜色这样应该 OK，暂时不提出来
            # if (50 < pixel[0] < 60) and (53 < pixel[1] < 63) and (95 < pixel[2] < 110):
            if (50 < pixel[2] < 60) and (53 < pixel[1] < 63) and (95 < pixel[0] < 110):
                piece_x_sum += j
                piece_x_c += 1
                piece_y_max = max(i, piece_y_max)

    if not all((piece_x_sum, piece_x_c)):
        return 0, 0, 0, 0
    piece_x = piece_x_sum / piece_x_c
    piece_y = piece_y_max - piece_base_height_1_2  # 上移棋子底盘高度的一半

    for i in range(target_h_start,h - target_h_start,2):
        last_pixel = im[i,0]
        # last_pixel = im.getpixel((0, i))
        if board_x or board_y:
            break
        board_x_sum = 0
        board_x_c = 0

        for j in range(target_w_start , w - target_w_start , 2):
            pixel = im[i,j]
            # pixel = im.getpixel((j, i))
            # 修掉脑袋比下一个小格子还高的情况的 bug
            if abs(j - piece_x) < piece_body_width:
                continue

            # 修掉圆顶的时候一条线导致的小 bug，这个颜色判断应该 OK，暂时不提出来
            if abs(int(pixel[0]) - int(last_pixel[0])) + abs(int(pixel[1]) - int(last_pixel[1])) + abs(int(pixel[2]) - int(last_pixel[2])) > 10:
                board_x_sum += j
                board_x_c += 1
        if board_x_sum and board_x_c > 4:
            board_x = board_x_sum / board_x_c
    # tan30
    board_y = piece_y - abs(board_x - piece_x) * math.sqrt(3) / 3

    if not all((board_x, board_y)):
        return 0, 0, 0, 0

    return piece_x, piece_y, board_x, board_y


def main():
    while True:
        pull_screenshot()
        # im = Image.open("./1.png")
        im = cv2.imread("./1.png")
        # 获取棋子和 board 的位置
        piece_x, piece_y, board_x, board_y = find_piece_and_board(im)
        ts = int(time.time())
        print(ts, piece_x, piece_y, board_x, board_y)
        jump(math.sqrt((board_x - piece_x) ** 2 + (board_y - piece_y) ** 2))
        # save_debug_creenshot(ts, im, piece_x, piece_y, board_x, board_y)
        # backup_screenshot(ts)
        time.sleep(random.uniform(1, 2.0)) # 为了保证截图的时候应落稳了，多延迟一会儿


if __name__ == '__main__':
    main()
